<template>
  <div class="flex ml-3 gap-8 flex-col">
    <el-form  label-position="left" ref="elForm" size="medium" label-width="100px">

      <el-form-item label="模式" label-width="120px">
        <select v-model="mode" placeholder="" class="w-[202px]" @change="changeMode">
          <option label="手动" value="manual"></option>
<!--          <option label="自动" value="auto"></option>-->
        </select>
      </el-form-item>
    </el-form>
    <div class="w-[427px] h-[349px] border-2 border-gray-300 relative">
      <video-player :id="3" class="object-fill w-full h-full" autoplay></video-player>
      <canvas
        ref="canvasRef"
        class="absolute top-0 left-0 insert-0 cursor-crosshair z-50 "
        @mousedown="handleMouseDown"
        @mouseup="handleMouseUp"
        @mouseleave="handleMouseLeave"
      ></canvas>    </div>
   <div class="flex gap-4 ml-24" v-show="mode === 'manual'">
     <div class="grid grid-cols-1 grid-rows-3 gap-2">
       <i></i>
        <div title="确认坏点" @click="handle(5)" class="a a1 p-2 border-[1px] border-gray-300 rounded-sm size-[32px] pt-8"></div>
       <i></i>
     </div>
     <div class="grid grid-cols-3 grid-rows-3 gap-2">
       <i></i>
       <span @click="handle(1)" class="a a2 p-2 border-[1px] border-gray-300 rounded-sm size-[32px]"></span>
       <i></i>
       <span @click="handle(2)" class="a a3 p-2 border-[1px] border-gray-300 rounded-sm size-[32px]"></span>
       <span title="保存" @click="handle(0)" class="a a4 p-2 border-[1px] border-gray-300 rounded-sm size-[32px]"></span>
<!--       <i/>-->
       <span @click="handle(3)" class="a a5 p-2 border-[1px] border-gray-300 rounded-sm size-[32px]"></span>
       <i></i>
       <span @click="handle(4)" class="a a6 p-2 border-[1px] border-gray-300 rounded-sm size-[32px]"></span>
       <i></i>
     </div>
     <div class="grid grid-cols-1 grid-rows-3 gap-2">
       <i></i>
       <div title="取消坏点" @click="handle(-1)" class="a a7 p-2 border-[1px] border-gray-300 rounded-sm size-[32px] pt-8"></div>
       <i></i>
     </div>
   </div>
  </div>
</template>

<script>
import {
  addBadpixel,
  badpixelMode,
  badpixelMove, cancelBadpixel,
  clearBadpixel,
  correctbadpixel,
  getbadpixelMode, getvideoparam, saveBadpixel
} from "../../../api/api";
import videoPlayer from "@/views/mini/videoplayer.vue";

export default {
  name: "xianshi",
  components: {
    videoPlayer,
  },
  data() {
    return {
      mode: 'manual',
      coordx: null, // X coordinate of the crosshair center on the canvas
      coordy: null, // Y coordinate of thecrosshair center on the canvas
      isDragging: false, // Flag to track mouse dragging state
      canvasCtx: null, // Canvas 2D rendering context
      videoStream: null, // To hold the MediaStream object
      videoError: null, // To display video errors
      canvasWidth: 423, // Canvas width, used for coordinate conversion
      canvasHeight: 345, // Canvas height, used for coordinate conversion
      crosshairSize: 15, // Size of the crosshair lines (radius)
      // The local moveStep is no longer needed as the API handles movement
      // moveStep: 5,
      width: 384,
      height: 288,
    };
  },
  mounted() {
    getvideoparam().then(res => {
      this.width = res.data.width
      this.height = res.data.height;
    })
    // Wait for the next tick to ensure refs are available
    this.$nextTick(() => {
      this.initCanvas();
    });
    getbadpixelMode().then(res => {
      if (res.code === 0) {
        this.mode = res.data.type;
      } else {
        this.$message.error(res.msg);
      }
    })
  },
  methods: {
    changeMode() {
      badpixelMode({
        type: this.mode
      }).then(res => {
        if (res.code === 0) {
          this.$message.success("操作成功");
        } else {
          this.$message.error("操作失败");
        }
      })
    },

    // Initialize Canvas
    initCanvas() {
      const canvas = this.$refs.canvasRef;
      if (canvas) {
        canvas.width = this.canvasWidth;
        canvas.height = this.canvasHeight;
        this.canvasCtx = canvas.getContext("2d");
        this.updateCanvas();
      } else {
        console.error("Canvas element not found.");
      }
    },

    /**
     * Converts canvas coordinates (e.g., 423x345) to target API coordinates (384x288).
     * @param {number} canvasX The X coordinate on the canvas.
     * @param {number} canvasY The Y coordinate on the canvas.
     * @returns {{x: number, y: number}} The converted integer coordinates.
     */
    convertCoordinates(canvasX, canvasY) {
      if (canvasX === null || canvasY === null) {
        return { x: null, y: null };
      }
      const targetWidth = this.width;
      const targetHeight = this.height;
      const convertedX = Math.round((canvasX / this.canvasWidth) * targetWidth);
      const convertedY = Math.round((canvasY / this.canvasHeight) * targetHeight);
      return { x: convertedX, y: convertedY };
    },

    // Clear the canvas
    clearCanvas() {
      if (!this.canvasCtx) return;
      this.canvasCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
    },

    // Draw the crosshair
    drawCrosshair() {
      if (!this.canvasCtx || this.coordx === null || this.coordy === null) {
        return;
      }
      const x = this.coordx;
      const y = this.coordy;
      const size = this.crosshairSize;
      this.canvasCtx.beginPath();
      this.canvasCtx.strokeStyle = "red";
      this.canvasCtx.lineWidth = 2;
      this.canvasCtx.moveTo(x - size, y);
      this.canvasCtx.lineTo(x + size, y);
      this.canvasCtx.moveTo(x, y - size);
      this.canvasCtx.lineTo(x, y + size);
      this.canvasCtx.stroke();
    },

    // Update Canvas (Clear and Redraw)
    updateCanvas() {
      // this.clearCanvas();
      // this.drawCrosshair();
    },

    // Ensure coordinates stay within canvas bounds
    clampCoordinates() {
      if (this.coordx !== null) {
        this.coordx = Math.max(0, Math.min(this.canvasWidth, this.coordx));
      }
      if (this.coordy !== null) {
        this.coordy = Math.max(0, Math.min(this.canvasHeight, this.coordy));
      }
    },

    // Handle button clicks
    handle(num) {
      // For any action requiring a coordinate, first check if a point has been selected.
      if (this.coordx === null || this.coordy === null) {
        this.$message.warning("请先在画面上选择一个点");
        return;
      }

      // All actions will use the same converted coordinates.
      const { x: convertedX, y: convertedY } = this.convertCoordinates(this.coordx, this.coordy);

      switch (num) {
        case 1: // Up
          addBadpixel({ coordx: convertedX, coordy: convertedY - 1 }).then(
            res => {
              if (res.code === 0){
                this.coordy -= 1;
                // this.$message.success("操作成功");
              } else {
                this.$message.error("操作失败");
              }
            }
          );
          break;
        case 2: // Left
          addBadpixel({ coordx: convertedX - 1, coordy: convertedY }).then(
            res => {
              if (res.code === 0){
                this.coordx -= 1;
                // this.$message.success("操作成功");
              } else {
                this.$message.error("操作失败");
              }
            }
          );
          break;
        case 3: // Right
          addBadpixel({ coordx: convertedX + 1, coordy: convertedY }).then(
            res => {
              if (res.code === 0){
                this.coordx += 1;
                // this.$message.success("操作成功");
              } else {
                this.$message.error("操作失败");
              }
            }
          );
          break;
        case 4: // Down
          addBadpixel({ coordx: convertedX, coordy: convertedY + 1 }).then(
            res => {
              if (res.code === 0){
                this.coordy += 1;
                // this.$message.success("操作成功");
              } else {
                this.$message.error("操作失败");
              }
            }
          );
          break;
        case 5: // Confirm bad pixel
          correctbadpixel({
            coordx: convertedX,
            coordy: convertedY,
          }).then(res => {
            if (res.code === 0){
              this.$message.success("操作成功");
            } else {
              this.$message.error("操作失败");
            }
          });
          break;
        case 0: // Save
          console.log("Saving point:", { x: this.coordx.toFixed(2), y: this.coordy.toFixed(2) });
          saveBadpixel({
            coordx: convertedX,
            coordy: convertedY,
          }).then(res => {
            if (res.code === 0){
              this.$message.success("操作成功");
            } else {
              this.$message.error("操作失败");
            }
          });
          return;
        case -1: // Cancel/Delete
          cancelBadpixel({
            coordx: convertedX,
            coordy: convertedY,
          }).then(res => {
            if (res.code === 0){
              this.$message.success("操作成功");
              this.coordx = null;
              this.coordy = null;
            } else {
              this.$message.error("操作失败");
            }
          });

          break;
        default:
          console.warn("Unknown handle command:", num);
          return;
      }

      // Redraw the canvas to reflect any changes
      this.updateCanvas();
    },

    // --- Mouse Event Handlers for Point Selection ---

    handleMouseDown(event) {
      // Set the point position directly on click
      this.coordx = event.offsetX;
      this.coordy = event.offsetY;
      this.clampCoordinates();
      this.updateCanvas();
    },

    handleMouseMove(event) {
      // This is for drag functionality, currently inactive but can be enabled by setting isDragging.
      if (!this.isDragging) return;
      this.coordx = event.offsetX;
      this.coordy = event.offsetY;
      this.clampCoordinates();
      this.updateCanvas();
    },

    handleMouseUp(event) {
      this.coordx = event.offsetX;
      this.coordy = event.offsetY;
      this.clampCoordinates();
      this.updateCanvas();
      this.isDragging = false;

      // Convert coordinates to target resolution (384x288) and send to API
      const { x: convertedX, y: convertedY } = this.convertCoordinates(this.coordx, this.coordy);

      addBadpixel({
        coordx: convertedX,
        coordy: convertedY,
      }).then(res => {
        if (res.code === 0){
          this.$message.success("操作成功");
        } else {
          this.$message.error("操作失败");
        }
      });
      console.log("Mouse up. Canvas position:", { x: this.coordx, y: this.coordy }, "Converted:", { x: convertedX, y: convertedY });
    },

    handleMouseLeave() {
      if (this.isDragging) {
        this.isDragging = false;
        console.log("Mouse left canvas during drag. Final position:", { x: this.coordx, y: this.coordy });
      }
    },
  },
  beforeDestroy() {
    clearBadpixel()
  },
}
</script>

<style scoped>
.a {
  cursor: pointer;
}
.a1 {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
  visibility: visible;
  cursor: pointer;
  margin: 0;
  padding: 0;
  -webkit-text-size-adjust: none;
  display: inline-block;
  width: 32px;
  height: 32px;
  background-position: -292px -21px;
  background-image: url("~@/assets/images/ptz.png");
}
.a2 {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
  visibility: visible;
  cursor: pointer;
  margin: 0;
  padding: 0;
  -webkit-text-size-adjust: none;
  display: inline-block;
  width: 32px;
  height: 32px;
  background-position: -30px 0px;
  background-image: url("~@/assets/images/ptz.png");
}
.a3 {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
  visibility: visible;
  cursor: pointer;
  margin: 0;
  padding: 0;
  -webkit-text-size-adjust: none;
  display: inline-block;
  width: 32px;
  height: 32px;
  background-position: 0px -30px;
  background-image: url("~@/assets/images/ptz.png");
}
.a4 {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
  visibility: visible;
  cursor: pointer;
  margin: 0;
  padding: 0;
  -webkit-text-size-adjust: none;
  display: inline-block;
  width: 32px;
  height: 32px;
  background-position: -292px -75px;
  background-image: url("~@/assets/images/ptz.png");
}
.a5 {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
  visibility: visible;
  cursor: pointer;
  margin: 0;
  padding: 0;
  -webkit-text-size-adjust: none;
  display: inline-block;
  width: 32px;
  height: 32px;
  background-position: -60px -30px;
  background-image: url("~@/assets/images/ptz.png");
}
.a6 {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
  visibility: visible;
  cursor: pointer;
  margin: 0;
  padding: 0;
  -webkit-text-size-adjust: none;
  display: inline-block;
  width: 32px;
  height: 32px;
  background-position: -30px -59px;
  background-image: url("~@/assets/images/ptz.png");
}
.a7 {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
  visibility: visible;
  cursor: pointer;
  margin: 0;
  padding: 0;
  -webkit-text-size-adjust: none;
  display: inline-block;
  width: 32px;
  height: 32px;
  background-position: -292px -49px;
  background-image: url("~@/assets/images/ptz.png");
}
</style>
